import { defineComponent, ref, reactive } from "vue";
import styles from "./editPopup.module.less";
import LPopup from "@/components/public/lPopup/lPopup";
import _ from "lodash";
import { $insuranceGetList } from "@/api/search/search";
import { $insuranceAttrList, $attrValues } from "@/api/systemConfiguration/systemConfiguration";
import { message } from "ant-design-vue";

export default defineComponent({
  props: {
    service: {
      type: Object,
      required: true,
    },
  },
  emits: ["confirm"],
  setup(props, { emit, expose }) {
    const formDefault = {
      id: '',
      insurance_id: null,//名称
      attr_list: [] as any,//属性列表
    }
    const state = reactive({
      form: _.cloneDeep(formDefault),
      product: [] as any[],
      attrList: [] as any[],
    })
    const confirmLoading = ref(false as any);
    const editPopupRef = ref(null as any);
    //打开弹窗
    const open = async (record: any) => {
      editPopupRef.value.open();
      await getProductList();
      await getAttrList();
      if (record) {
        state.form.id = record.id;
        state.form.insurance_id = record.insurance_id;
        getAttrValues(record.insurance_id);
      }
    }
    //关闭弹窗
    const close = () => {
      editPopupRef.value.close();
    };
    // 初始化弹窗状态
    const init = () => {
      state.form = _.cloneDeep(formDefault);
      state.product = [];
      state.attrList = [];
    }
    // 获取产品列表
    const getProductList = () => {
      return new Promise((resolve) => {
        $insuranceGetList().then((res: any) => {
          state.product = res?.data?.map((x: any) => {
            return {
              label: x.name,
              value: x.id,
            };
          });
        }).finally(() => {
          resolve(true);
        })
      })
    }
    // 获取属性列表
    const getAttrList = () => {
      return new Promise((resolve) => {
        $insuranceAttrList().then((res: any) => {
          state.attrList = res?.data?.data?.map((x: any) => {
            return {
              type: x.type,
              label: x.name,
              value: x.id,
              units: x.units,
            };
          })
        }).finally(() => {
          resolve(true);
        })
      })
    }
    // 获取详细信息
    const getAttrValues = (insurance_id: number) => {
      $attrValues({
        insurance_id
      }).then((res: any) => {
        state.form.attr_list = res.data.map((x: any) => {
          return {
            type: x.type,
            label: x.name,
            value: x.attr_id,
            units: state.attrList?.find?.((y: any) => y.value === x.attr_id)?.units || [],
            attr_value: x.attr_value.map((y: any) => {
              return {
                value: y.split("@")[0],
                unit: y.split("@")[1] || null
              }
            })
          }
        });
      })
    }
    // 属性添加
    const attrChange = (option: any) => {
      const attrList = _.cloneDeep(state.form.attr_list);
      state.form.attr_list = option.map((x: any) => {
        if (x.type === 'area') {
          x.attr_value = [
            {
              value: null,
              unit: null,
            },
            {
              value: null,
              unit: null,
            }
          ];
        } else {
          x.attr_value = [
            {
              value: null,
              unit: null,
            }
          ];
        }
        return x;
      });
      attrList.forEach((x: any) => {
        if (state.form.attr_list.map((y: any) => y.value).includes(x.value)) {
          state.form.attr_list[state.form.attr_list.findIndex((y: any) => y.value === x.value)].attr_value = x.attr_value;
        }
      })
    }
    // 提交
    const submit = () => {
      confirmLoading.value = true;
      let param = _.cloneDeep(state.form);
      param.attr_list = param.attr_list.map((x: any) => {
        return {
          attr_id: x.value,
          attr_value: x.attr_value.map((y: any) => {
            let value = y.value;
            if (y.unit) {
              y.value = `${value}@${y.unit}`;
            }
            return y.value;
          })
        };
      })
      if (param.id) {
        props.service.edit(param).then((res: any) => {
          message.success("编辑属性成功");
          close();
        }).finally(() => {
          confirmLoading.value = false;
        })
      } else {
        props.service.add(param).then((res: any) => {
          message.success("添加属性成功");
          close();
        }).finally(() => {
          confirmLoading.value = false;
        })
      }
      emit("confirm");
    }
    expose({
      open,
      close,
    })

    // 属性内容
    const AttrValue: any = (attrValueProps: any) => {
      if (attrValueProps.item.type === 'area') {
        return (
          <div class={styles['attr-value']}>
            <div class={styles['value-area']}>
              <a-input placeholder="请输入..." class={styles['area-input']} size="small" v-model:value={attrValueProps.item.attr_value[0].value} />
              {attrValueProps.item.units?.length > 0 && <a-select class={styles['area-select']} size="small" placeholder="请选择" v-model:value={attrValueProps.item.attr_value[0].unit} options={attrValueProps.item.units.map((x: any) => {
                x = {
                  label: x.name,
                  value: x.mark,
                }
                return x;
              })} />}
              <span>-</span>
              <a-input placeholder="请输入..." class={styles['area-input']} size="small" v-model:value={attrValueProps.item.attr_value[1].value} />
              {attrValueProps.item.units?.length > 0 && <a-select class={styles['area-select']} size="small" placeholder="请选择" v-model:value={attrValueProps.item.attr_value[1].unit} options={attrValueProps.item.units.map((x: any) => {
                x = {
                  label: x.name,
                  value: x.mark,
                }
                return x;
              })} />}
            </div>
          </div>
        )
      } else if (attrValueProps.item.type === 'list') {
        return (
          <div class={styles['attr-value']}>

          </div>
        )
      } else {
        return (
          <div class={styles['attr-value']}>
            <div class={styles['value-string']}>
              <a-input class={styles['string-input']} size="small" v-model:value={attrValueProps.item.attr_value[0].value} />
              {attrValueProps.item.units?.length > 0 && <a-select class={styles['area-select']} size="small" placeholder="请选择单位" v-model:value={attrValueProps.item.attr_value[0].unit} options={attrValueProps.item.units.map((x: any) => {
                x = {
                  label: x.name,
                  value: x.mark,
                }
                return x;
              })} />}
            </div>
          </div>
        )
      }
    }

    return () => (
      <LPopup title={state.form.id ? "编辑属性" : "添加属性"} ref={editPopupRef} onClosed={() => {
        init();
      }}>
        <div class={styles['edit-popup']}>
          <div class={styles['select-rows']}>
            <div class={styles['select-row']}>
              <span class={styles['label']}>险种名称</span>
              <a-select
                class={styles['selector']}
                v-model:value={state.form.insurance_id}
                options={state.product}
                placeholder="请选择产品"
              ></a-select>
            </div>
            <div class={styles['select-row']}>
              <span class={styles['label']}>属性</span>
              <a-select
                class={styles['selector']}
                mode="multiple"
                value={state.form.attr_list.map((x: any) => x.value)}
                onChange={(value: any, option: any) => { attrChange(option) }}
                filter-option={(input: string, option: any) => option.label.indexOf(input) >= 0}
                options={state.attrList}
                placeholder="请选择属性"
              ></a-select>
            </div>
          </div>
          <div class={styles.list}>
            {
              state.form.attr_list.map((item: any) => (
                <div class={styles.item}>
                  <span class={styles['item-label']}>{item.label}</span>
                  <AttrValue item={item} />
                </div>
              ))
            }
          </div>
          <div class={styles['footer']}>
            <a-button onClick={() => { close() }}>取消</a-button>
            <a-button loading={confirmLoading.value} type="primary" onClick={() => { submit() }}>确认</a-button>
          </div>
        </div>
      </LPopup>
    )
  }
})